package com.godyao.mall.seckill.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.godyao.mall.common.utils.AssertUtils;
import com.godyao.mall.rabbitmq.model.MqMsg;
import com.godyao.mall.rabbitmq.repository.MqMsgRepository;
//import com.godyao.mall.seckill.service.ISendMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author godyao
 * @date 2022/4/3
 */
//@Slf4j
//@Service
//public class SendMsgServiceImpl implements ISendMsgService {
//    @Autowired
//    private RabbitTemplate rabbitTemplate;
//
//    @Autowired
//    private MqMsgRepository mqMsgRepository;
//
//    @Override
//    public void sendMsg(String exchange, String routingKey, String data) {
//        // 消息入库 返回唯一ID
//        final MqMsg msg = MqMsg.builder()
//                .createTime(new Date())
//                .exchange(exchange)
//                .routingKey(routingKey)
//                .msg(data)
//                .updateTime(new Date())
//                .status(1)
//                .build();
//        final MqMsg save = mqMsgRepository.save(msg);
//        AssertUtils.assertTrue(ObjectUtil.isNotNull(save));
//        // 组装消息内容
//        buildAndSendMsg(msg, data, exchange, routingKey);
//    }
//
//    @Override
//    public void reSendMsg() {
//        // 查询消息表中未发送成功的消息 查找失败5次以及5次之内的消息
//        final List<MqMsg> mqMsgs = mqMsgRepository.listNoSendSuccess();
//        if (CollectionUtils.isEmpty(mqMsgs)) return;
//        for (MqMsg msg : mqMsgs) {
//            buildAndSendMsg(msg, msg.getMsg(), msg.getMsg(), msg.getRoutingKey());
//        }
//    }
//
//    /**
//     * 组装并且发送消息
//     * @param msg
//     * @param msg2
//     * @param msg3
//     * @param routingKey
//     */
//    private void buildAndSendMsg(MqMsg msg, String msg2, String msg3, String routingKey) {
//        // 组装消息内容
//        final MessageProperties messageProperties = new MessageProperties();
//        // 消息唯一ID，防止幂等问题
//        messageProperties.setMessageId(msg.getId().toString());
//        final Message message = new Message(msg2.getBytes(StandardCharsets.UTF_8), messageProperties);
//        // 发送消息，利用CorrelationDaa将ID传递下去
//        //这里不必try-catch 即使发送失败
//        rabbitTemplate.convertAndSend(msg3, routingKey, message, new CorrelationData(msg.getId().toString()));
//    }
//}
